from __future__ import print_function

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import NumericProperty, StringProperty,\
    ObjectProperty

from goblinoid.comments.commentmodal import CommentModal
from goblinoid.profile.profilemodal import ProfileModal

Builder.load_file('goblinoid/feed/kv/commentsnapshot.kv')


class CommentSnapshot(Label):
    index = NumericProperty()
    comment = ObjectProperty()
    comment_text = StringProperty()

    def on_comments(self, instance, comment):
        self.comment_text = '{0}: {1}'.format(
            comment['actor'], comment['content'])

    def open_actor_profile(self):
        activity = App.get_running_app().pump_service.inbox[self.index]
        profile = activity.actor
        profile_modal = ProfileModal(profile)
        profile_modal.open()


class ViewCommentsButton(Button):
    button_text = StringProperty()
    index = NumericProperty()
    count = NumericProperty()

    def on_count(self, instance, count):
        if count == 0:
            self.text = 'no comments yet, be the first!'
        elif count == 1:
            self.text = 'view this comment'
        else:
            self.text = 'view all {0} comments'.format(count)

    def open_comment_modal(self):
        cached_comment_modal = App.get_running_app().pump_service.comment_modals[self.index]
        if cached_comment_modal is None:
            activity = self.get_activity()
            comment_modal = CommentModal(activity, self.index)
            App.get_running_app().pump_service.comment_modals[self.index] = comment_modal
            comment_modal.open()
        else:
            cached_comment_modal.open()

    def get_activity(self):
        return App.get_running_app().pump_service.inbox[self.index]
